﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using OtherDevice;
using UserData;
using BaseDll;
using Sunny.UI;
using System.Diagnostics;
namespace StationDemo
{
    public class VersionTypeValue
    {
        public string str_SoftVersionName = "";
        public string str_SoftVersionValue = "";
        public DateTime Time_Generate = DateTime.Now;
        public List<DllTypeValue> List_dllVersionValue = new List<DllTypeValue>();
    }
    public struct DllTypeValue
    {
        public string str_DllName;
        public string str_DllVersion;
        public string str_DllVersionValue;
    }
    public enum DllType
    {
        BaseDll,
        CommonDlg,
        ModuleUnit,
        MotionLib,
    }

    public class SoftVersionMgr
    {
        private static SoftVersionMgr softVersionMgr = null;
        private static object obj = new object();
        string currentFile = Path.GetFullPath("..") + @"\_Updata\软件版本更替.xml";
        public string strSoftVision = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        public List<VersionTypeValue> list_VisionValue = new List<VersionTypeValue>();
        public static SoftVersionMgr GetInstance()
        {
            if (softVersionMgr == null)
            {

                lock (obj)
                {
                    softVersionMgr = new SoftVersionMgr();
                    return softVersionMgr;
                }

            }
            else
                return softVersionMgr;
        }
        public void Load()
        {
            if (!File.Exists(currentFile))
            {
                AccessJosnSerializer.ObjectToJson(currentFile, list_VisionValue);
            }
            Object obs = AccessJosnSerializer.JsonToObject(currentFile, typeof(List<VersionTypeValue>));
            if (obs != null)
            {
                list_VisionValue = (List<VersionTypeValue>)obs;
            }

        }

        public void Function_VersionCheck(UIForm form)
        {
            bool b_Exite = false;
            bool b_IsStrInfo = false;
            bool b_IsNotMainChanged = false;
            int nindex = 0;
            foreach (var item in list_VisionValue)
            {
                if (item.str_SoftVersionName == strSoftVision)
                {
                    b_Exite = true;
                    break;
                }
                nindex++;
            }

            foreach (var item in list_VisionValue)
            {
                if (item.str_SoftVersionName == strSoftVision && item.str_SoftVersionValue != "")
                {
                    b_IsStrInfo = true;
                    break;
                }
            }
            if (!b_IsStrInfo)
            {
                foreach (var item in list_VisionValue)
                {
                    string[] list_SoftVersion = item.str_SoftVersionName.Split('.');
                    string[] list_NowSoftVision = strSoftVision.Split('.');
                    if (list_SoftVersion[0] == list_NowSoftVision[0] &&
                       list_SoftVersion[1] == list_NowSoftVision[1] &&
                       list_SoftVersion[2] == list_NowSoftVision[2] )
                    {
                        b_IsNotMainChanged = true;
                        break;
                    }
                }

                string strValue = "";
                string strInfo = $"请输入当前软件版本信息：{strSoftVision}";
                //如果已存在具体描述，不再添加
                bool b_IsNewStrInfo = UIInputDialog.InputStringDialog(form, ref strValue, true, strInfo);
                if(b_Exite) 
                {
                    list_VisionValue[nindex].str_SoftVersionValue = strValue;
                }
                else
                {
                    VersionTypeValue visionType = new VersionTypeValue();
                    visionType.str_SoftVersionName = strSoftVision;
                    visionType.str_SoftVersionValue = strValue;
                    List<DllTypeValue> list_dllType = new List<DllTypeValue>();
                    if (list_VisionValue.Count != 0)
                    {
                        list_dllType = list_VisionValue.Last().List_dllVersionValue;
                    }
                    foreach (var item in Enum.GetNames(typeof(DllType)))
                    {
                        bool b_IsExistDll = false;
                        foreach (var item_dll in list_dllType)
                        {
                            if (item_dll.str_DllName == item)
                            {
                                b_IsExistDll = true;
                                break;
                            }
                        }
                        if (!b_IsExistDll)
                        {
                            DllTypeValue dllTypeValue = new DllTypeValue();
                            dllTypeValue.str_DllName = item;
                            string str_path = AppDomain.CurrentDomain.BaseDirectory;
                            string str_DllPath = str_path + $"\\{item}.dll";
                            FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(str_DllPath);
                            dllTypeValue.str_DllVersion = versionInfo.FileVersion;
                            dllTypeValue.str_DllVersionValue = "填写版本信息";
                            list_dllType.Add(dllTypeValue);
                        }
                    }
                    visionType.List_dllVersionValue = list_dllType;
                    list_VisionValue.Add(visionType);

                }
                AccessJosnSerializer.ObjectToJson(currentFile, list_VisionValue);
                //若有数据填入，则备份程序exe和dll
                if (b_IsNewStrInfo)
                {
                    Function_运行程序和dll备份();
                }
                //dll检查
                if (!b_IsNotMainChanged && !b_IsNewStrInfo)
                {
                    System.Environment.Exit(0);
                    UserConfig.CloseHardWork();
                }

            }


            //dll检查
            if (!Function_DllVersionCheck())
            {
                System.Environment.Exit(0);
                UserConfig.CloseHardWork();
            }
            
        }

        private bool Function_DllVersionCheck()
        {
            foreach (var item in Enum.GetNames(typeof(DllType)))
            {
                string str_path = AppDomain.CurrentDomain.BaseDirectory;
                string str_DllPath = str_path + $"\\{item}.dll";
                if(!File.Exists(str_DllPath))
                {
                    UIMessageBox.ShowError($"运行目录下不存在：{item}.dll，请确认运行环境");
                    return false;
                }
                else
                {
                    FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(str_DllPath);
                    foreach (var item_SoftVision in list_VisionValue)
                    {
                        foreach (var item_dllVersion in item_SoftVision.List_dllVersionValue)
                        {
                            if(item_dllVersion.str_DllName==item)
                            {
                                if (versionInfo.FileVersion == item_dllVersion.str_DllVersion)
                                    break;
                                else
                                {
                                    UIMessageBox.ShowError($"{item}.dll，当前版本={versionInfo.FileVersion}，所需版本={item_dllVersion.str_DllVersion},请确认运行环境");
                                    return false;
                                }
                            }
                        }
                    }

                }

            }
            return true;
        }
        public bool Function_运行程序和dll备份()
        {
            string path = Path.GetFullPath("..")+ $"\\_Updata\\软件更替历史版本\\{strSoftVision}\\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (var item in Enum.GetNames(typeof(DllType)))
            {
                string str_sourceDllPath=AppDomain.CurrentDomain.BaseDirectory + $"{item}.dll";
                string str_DllPath = path + $"{item}.dll";
                File.Copy(str_sourceDllPath, str_DllPath,true);
            }
            string str_sourceEXEPath = Process.GetCurrentProcess().MainModule.FileName;
            string str_EXEPath = path + Path.GetFileName(str_sourceEXEPath);
            File.Copy(str_sourceEXEPath, str_EXEPath);
            return true;
        }
    }
}